package com.simonall.netty.handler;

import com.simonall.enums.ResponseCodeEnum;
import com.simonall.netty.handler.beans.ReqSimplePrint;
import com.simonall.netty.resolver.impl.BodyParamResolver;
import com.simonall.netty.resolver.impl.PathParamResolver;
import com.simonall.print.PrintHandler;
import com.simonall.print.SimplePdfPrintHandler;
import com.simonall.utils.NettyResponseUtil;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.ObjectUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;

/**
 * Http 处理器
 * 
 * @author simonall
 */
public class SimpleHttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
		ReqSimplePrint param = requestParam(request);
		String url = param.getUrl();
		Integer copies = param.getCopies();
		try {
			// 是否自助打印
			if (param.isDialog()) { // 打印对话框
				// new SimpleManualPrintHandler().print(bytes, copies);
			} else {
				String fileSuffix = FileNameUtil.getSuffix(url);
				PrintHandler handler = PrintHandler.adapter(fileSuffix);
				if (ObjectUtil.isNull(handler)) {
					handler = new SimplePdfPrintHandler();
				}
				handler.print(url, handler.defaultService(), copies);
			}
		} catch (Exception e) {
			NettyResponseUtil.build(ctx, ResponseCodeEnum.UNKNOWN_ERROR);
		}
		NettyResponseUtil.build(ctx, ResponseCodeEnum.SUCCESS);
	}

	/**
	 * 请求参数
	 * 
	 * @return
	 */
	private final ReqSimplePrint requestParam(FullHttpRequest request) {
		ReqSimplePrint param = null;
		HttpMethod method = request.method();
		if (method.equals(HttpMethod.GET)) { // GET
			param = new PathParamResolver().resolver(request, ReqSimplePrint.class);
		} else if (method.equals(HttpMethod.POST)) { // POST
			param = new BodyParamResolver().resolver(request, ReqSimplePrint.class);
		}
		return param;
	}
}
